//$("#size-picker").height($("#colour-picker").height());
//$("#quantity").height($("#colour-picker").height());

function ajax_logochange_save( row, ab, updating )
{	
    var xmlHttp;

    try
    {
	xmlHttp = new XMLHttpRequest();
    }
    catch(e)
    {
	try
	{
		xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
	}
	catch(e)
	{
		try
		{
			xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
		}
		catch(e)
		{
			alert("Your browser does not support AJAX!");
			return false;
		}
	}
    }

    //Bind what to do when the request completes
    xmlHttp.onreadystatechange = function()
    {
		if(xmlHttp.readyState == 4)
		{
			//redraw the basket
			$("#BasketDiv").html(xmlHttp.responseText);

			//Redraw the selects
			redrawSelects( true );
		}
    };

    other = 'B';
    if(ab == 'B'){other = 'A';}

    if(updating == "logo")
    {
		logo = document.getElementsByName( "logo"+ab+row )[0];
		logo = logo.value;
		var url = "ajax_update_logo.asp?area=checkout&stage=logo&u=logo"+ ab +"&r=" + row + "&ab=" + ab + "&logo"+ ab +"=" + logo;
    }
    else if(updating == "logoPos")
    { 
		logopos = document.getElementsByName( "logo"+ ab +"pos"+row )[0];	
		logopos = logopos.value;
		
		// Carefull! The radio indexes start at 0, so embroidered = 0, transfer = 1.
			// However, this should be embroidered = 1, transfer = 2... So, +1.
		var logoType = getSelectedRadio(document.getElementsByName("Logo" + ab + "Type" + row)) + 1;

		logoposother = document.getElementsByName( "logo"+other+"pos"+row )[0];
		logoposother = logoposother.value;

		if(logoposother == "K" && logoType == 2)
		{
			logopos = "L";
			document.getElementsByName( "logo"+ ab +"pos"+row )[0].selectedIndex=5;
		}

		var url = "ajax_update_logo.asp?area=checkout&stage=logo&u=pos"+ ab +"&r=" + row + "&ab=" + ab + "&logo"+ ab +"pos="+ logopos + "&logo"+ ab +"Type=" + logoType;

    }
    else if(updating == "logoType")
    {
		// Carefull! The radio indexes start at 0, so embroidered = 0, transfer = 1.
		// However, this should be embroidered = 1, transfer = 2... So, +1.
		var logoType = getSelectedRadio(document.getElementsByName("Logo" + ab + "Type" + row)) + 1;
		logopos = document.getElementsByName( "logo"+ ab +"pos"+row )[0];
		logopos = logopos.value;

		logoposother = document.getElementsByName( "logo"+other+"pos"+row )[0];
		logoposother = logoposother.value;

		if(logoposother == "K")
		{
			logopos = "L";
			document.getElementsByName( "logo"+ ab +"pos"+row )[0].selectedIndex=5;
		}

		var url = "ajax_update_logo.asp?area=checkout&stage=logo&u=logotype"+ ab +"&r=" + row + "&ab=" + ab + "&logo"+ ab +"type=" + logoType + "&logo"+ ab +"pos="+ logopos;
    }
	
	//If we're doing this from a product page ($("#BasketDiv") doesn't exist), we need to change the URL.
	//We're coming from a different place, and we need to tell it not to set cookies. The cookies are done
	//by basket line #. which we don't have; this breaks things and gives odd behaviour, so we do the cookies
	//ourselves when we're on  a product page.
		url = "../" + url;
		//If we're actually on the basket page, we DO want cookies.
		//if(!$("#basketview").length)
		if(!$("#shopping-cart-table").length)
		{
			url = url + "&nc=y";
		}
 
    xmlHttp.open("GET",url,true);
    xmlHttp.send(null);

} //end function

$(document).ready(function(){
    redrawSelects( false );
	
	
	if($('#basketview').length)
	{
		$.each($('div.logoplace'), function(){
			haslogo = false;
			$.each($(this).find("select[name^='logo']"), function(){
				if(!haslogo && !$(this).hasClass('logoselect'))
				{
					haslogo = ( $(this).val() != '0');
				}
			});
			
			if(haslogo)
			{
				$(this).children('div.logoplacetop').children('span.logoheader').html('Logos');
			}
		});
	}
	
	//Disable the heat transfer option if the selected logo can't be heat transfered
	$.each($(this).find("select[name^='logo']"), function(){
		if(!$(this).hasClass('logoselect'))
		{
			option = $(this).children('option:selected');
			
			if( option.attr('ht') == 'false' )
			{
				name = $(this).attr('name').substring(1, ($(this).attr('name').length-1));
				row = $(this).attr('name').substring($(this).attr('name').length-1);
			}
		}
	});
});

function redrawSelects( fromajax )
{
    $("select.logoselect").each(function(index, data){
    	var try2digit = $(this).attr('name').charAt($(this).attr('name').length-2);

    	if ( isNaN(parseInt(try2digit)) ) {
    		row = ( $(this).attr('name').charAt($(this).attr('name').length-1) );
    		console.log('row:'+row+parseInt(try2digit));
    	}
    	else {
			row = ( $(this).attr('name').charAt($(this).attr('name').length-2) + $(this).attr('name').charAt($(this).attr('name').length-1));
			console.log('row:'+row);
		}
		ab='A';	other='B';
		
		thislogo = $("[name='logoA"+row+"']").val();
		otherlogo = $("[name='logoB"+row+"']").val();
		
		var thislogoASelected =$("[name='logoA"+row+"']").find('option:selected'); 
        var thislogoAht = thislogoASelected.attr("ht"); 
        
		var thislogoBSelected =$("[name='logoB"+row+"']").find('option:selected'); 
        var thislogoBht = thislogoBSelected.attr("ht"); 

		//Store both logo positions
		thisposselect = $("[name='logo"+ab+"pos"+row+"']");
		otherposselect = $("[name='logo"+other+"pos"+row+"']");
		thispos = thisposselect.val();
		otherpos = otherposselect.val();
		
		//If both logos are selected, redraw the selects, without the position selected by the other
		if( (thislogo!=0) && (otherlogo!=0) )
		{
			//The positions have overlapped, sort it out.
			if(thispos==otherpos)
			{
				selectlength = thisposselect.children().length;
				//The .index selector isn't behaving and I want this done, so it's using a .each hack
				thisposselect.children().each(function(index, data){
				if( $(this).val()==thispos )
				{
					if(index == (selectlength-1))
					{
						otherposselect.val( otherposselect.children().eq(index-1) );
						otherpos = otherposselect.val();
					}
					else
					{
						otherposselect.val( otherposselect.children().eq(index+1).val() );
						otherpos = otherposselect.val();
					}
				}
			});
				if(!fromajax)
				{					
					ajax_logochange_save( row, ab, "logoPos" );
				}
			}
			
			//Figure out what's a valid value for each of the selects
			thisvalids = new Array();
			othervalids = new Array();

			valids = ["-","A","C","F","I","K","L","M","N","O","R"];
			if(($("[name='LogoBType"+row+"']:checked").val()=="2") && (thislogoBht == "true")){ valids = ["K","L"]; }
			$.each(valids, function(index,value){
				if(value != thisposselect.val()){othervalids.push(value)}
			});
			
			valids = ["A","C","F","I","K","L","M","N","O","R"];
			if(($("[name='LogoAType"+row+"']:checked").val()=="2") && (thislogoAht == "true")){ valids = ["K","L"]; }
			$.each(valids, function(index,value){
				if(value != otherposselect.val()){thisvalids.push(value)}
			});

			thisposselect.empty();
			$.each(thisvalids, function(index, data){
				thisposselect.append('<option value="'+data+'">'+data+'</option>');
				if(data==thispos){thisposselect.val(data);}
			});
			
			otherposselect.empty();
			$.each(othervalids, function(index, data){
				otherposselect.append('<option value="'+data+'">'+data+'</option>');
				if(data==otherpos){otherposselect.val(data);}
			});

		}
		else //Else, redraw the selects with all relevant positions
		{
			thisposselect.empty();
			otherposselect.empty();
			
			//If this is set to a heat transfer, only allow K & L
			valids = ["A","C","F","I","K","L","M","N","O","R"];
			if(($("[name='LogoAType"+row+"']:checked").val()=="2") && (thislogoAht == "true")){ valids = ["K","L"]; }
			$.each(valids, function(index,data){
				thisposselect.append('<option value="'+data+'">'+data+'</option>');
				if(data==thispos){thisposselect.val(data);}
			});

			//If this is set to a heat transfer, only allow K & L
			valids = ["A","C","F","I","K","L","M","N","O","R"];
			if(($("[name='LogoBType"+row+"']:checked").val()=="2") && (thislogoAht == "true")){ valids = ["K","L"]; }
			$.each(valids, function(index,data){
				otherposselect.append('<option value="'+data+'">'+data+'</option>');
				if(data==otherpos){otherposselect.val(data);}
			});
		}
    });
}

function getSelectedRadio(buttonGroup) {
    // returns the array number of the selected radio button or -1 if no button is selected
    if (buttonGroup[0]) { // if the button group is an array (one button is not an array)
	for (var i=0; i<buttonGroup.length; i++) {
	    if (buttonGroup[i].checked) {
		return i
	    }
	}
    } else {
	if (buttonGroup.checked) {return 0;} // if the one button is checked, return zero
    }
    // if we get to this point, no radio button is selected
    return -1;
} // Ends the "getSelectedRadio" function

function logoChange( row, ab )
{
	if($('#logo'+ab+row).children('option:selected').attr('ht') == 'true')
	{
		//$('#Logo'+ab+'Type'+row+'h').removeAttr('disabled');
	}
	else
	{
		$('#Logo'+ab+'Type'+row).click();
		//$('#Logo'+ab+'Type'+row+'h').attr('disabled', 'true');
	}
	
	//call ajax save
    ajax_logochange_save( row, ab, "logo" );    
}

function logoTypeChange( row, ab )
{   
	redrawSelects(false);
	
	//call ajax save
    ajax_logochange_save( row, ab, "logoType" );
}

function logoposChange( row, ab )
{
	redrawSelects(false);
    //call ajax save
    ajax_logochange_save( row, ab, "logoPos" );
}

function logoposWarnClose()
{
	var divid = document.getElementById('logoPosClash');
	divid.style.display = "none";
}

var showimage = '../img/show.gif';
var hideimage = '../img/hide.gif';

function toggleLogoDiv( element )
{
	$.each(element.children('div'), function(){
		if(!$(this).hasClass('logoplacetop') && !$(this).is(':animated'))
		{
			$(this).slideToggle();
			img = element.children('div.logoplacetop').children('img');
	
			if(img.attr('src') != hideimage)
			{
				element.find('span.clickhere').html('Click to Hide');
				
				img.attr('src', hideimage);
			}
			else
			{
				element.find('span.clickhere').html('Click to Show');
				
				img.attr('src', showimage);
			}
		}
	});
}


function validateLogoForm()
{	
	var myLogo = document.getElementById("logoB1").selectedIndex;
	var myLogoVal = document.getElementById("logoB1")[myLogo].value;
	if (myLogoVal!="0")
	{
		var myChoice = document.getElementById("logoBpos1").selectedIndex;
		var myVal = document.getElementById("logoBpos1")[myChoice].value;
		if (myVal=="-")
		{
			alert("Please select a logo B position");
			return false;
		}
	}
}

function validateLogoFormBasket()
{
	alert('func start');
		$.each($('div.logoplace'), function(){
			haslogo = false;
			$.each($(this).find("select[name^='logo']"), function(){
				if(!haslogo && !$(this).hasClass('logoselect'))
				{
					haslogo = ( $(this).val() != '0');
					alert($(this).val());
				}
			});
			
			if(haslogo)
			{
				otherpos = otherposselect.val();
				alert('\notherpos'+otherpos);
			}
		});
 
}